/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.matchers;

import java.util.Arrays;
import java.util.List;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.parsing.Tokenizer;
import tal.drivechain.variable.types.DataType;

/**
 *
 * @author Main
 */
public class ArrayMatcher extends ValueMatcher {
    ValueMatcher[] matchers;
    DataType type;
    
    public ArrayMatcher(DataType type) {
        this.type = type;
    }
    
    @Override
    protected void parseSpecial(String pattern) throws IllegalArgumentException {
        Tokenizer tokenizer = new Tokenizer(pattern, ',');
        String[] tokens = tokenizer.getTokens();
        matchers = new ValueMatcher[tokens.length];
        for (int i=0; i<matchers.length; i++) { 
            matchers[i] = type.createValueMatcher();
            matchers[i].parsePattern(tokens[i]);
        }
    }

    @Override
    protected boolean matchSpecial(Object value, ChainNode context) throws IllegalArgumentException {
        List<Object> val = (List<Object>)value;
        if (matchers.length>val.size()) return false;
        for (int i=0; i<matchers.length; i++)
            if (!matchers[i].matches(val.get(i), context)) return false;
        return true;
    }

    @Override
    public String toString() {
        String ret = "";
        for (ValueMatcher m : matchers) ret += m.toString() + ", ";
        return ret.substring(0, ret.length()-2);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ArrayMatcher) {
            if (super.equals(obj)) return true;
            else {
                ArrayMatcher that = (ArrayMatcher)obj;
                for (int i=0; i<this.matchers.length; i++)
                    if (this.matchers[i]!=that.matchers[i]) return false;

                return (this.type.equals(that.type));
            }
        } else return false;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + Arrays.deepHashCode(this.matchers);
        hash = 29 * hash + (this.type != null ? this.type.hashCode() : 0);
        return hash;
    }
}
